//
//  VideoListViewController.m
//  RoadKnowEntertainment
//
//  Created by lanou on 16/8/5.
//  Copyright © 2016年 RKE. All rights reserved.
//

#import "VideoListViewController.h"
#import "ViewListTableViewCell.h"
#import <MediaPlayer/MediaPlayer.h>
#import "PlayViewController.h"
#import "UMSocial.h"
#import "FavorManager.h"
#import <MJRefresh.h>
@interface VideoListViewController ()<UITableViewDelegate, UITableViewDataSource,UMSocialUIDelegate>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataArray;

@property (nonatomic, assign)BOOL isSelect;

@property (nonatomic, assign)NSInteger limit;

@end

@implementation VideoListViewController

- (void)viewWillAppear:(BOOL)animated {
   
    
}
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        self.limit = 0;
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.isSelect = false;
    [self initTableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"ViewListTableViewCell" bundle:nil] forCellReuseIdentifier:@"videoCell"];
    self.tableView.separatorColor = UITableViewCellSeparatorStyleNone;
    self.navigationItem.title = @"视频";
//    [self requestData];
    [self refreshData];
    
    
}

- (void)requestData {
    
    [NetWorkRequestManager requestWithType:GET urlString:kVideoUrl parDic:nil finish:^(NSData *data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dict[@"V9LG4B3A0"];
        for (NSMutableDictionary *dic in array) {
            VideoListModel *model = [[VideoListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            if ([model.title containsString:@"【"] && [model.title containsString:@"】"]) {
                model.title = [model.title substringFromIndex:14];
            }
            [self.dataArray addObject:model];
        }
        [self endRefresh];
        self.limit = self.limit + 1;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        NSLog(@"%@", self.dataArray);
    } finishError:^(NSError *error) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"您的网络不给力!";
        [hud hide: YES afterDelay: 2];
    }];
    
    
}

- (void)refreshData {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.dataArray removeAllObjects];
        [self requestData];
        
    }];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        NSLog(@"%ld", self.limit);
        [self requestData];
        //111
    }];
}


// 结束更新 隐藏刷新
- (void)endRefresh
{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)initTableView {
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (void)playAndPauseAction:(UIButton *)button {
    

//    self.tabBarController.tabBar.alpha = 0;
    
    VideoListModel *model = self.dataArray[button.tag - 100];
    PlayViewController *playerVC = [[PlayViewController alloc] init];
    playerVC.movieUrlString = model.mp4_url;
    playerVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:playerVC animated:YES];
    playerVC.hidesBottomBarWhenPushed = NO;
    

    self.hidesBottomBarWhenPushed = YES;
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController pushViewController:playerVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)shareAction:(UIButton *)button {
    
    VideoListModel *model = self.dataArray[button.tag - 300];
    AVUser *user = [AVUser currentUser];
    if (user != nil) {
        [UMSocialData defaultData].extConfig.title = model.title;
        [UMSocialData defaultData].extConfig.qqData.url = @"http://baidu.com";
         [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeVideo url:model.mp4_url];
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"57873da867e58e72f6000c9e"
                                          shareText:@"路晓娱乐，世界被你知晓"
                                         shareImage:[UIImage imageNamed:@"icon"]
                                    shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToSina,UMShareToQQ,UMShareToQzone]
                                           delegate:self];
    }else {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"未检测到登录用户,请登录!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:action];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    
}

- (void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response {
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}
- (void)favorAction:(UIButton *)button {
    NSInteger index = button.tag - 200;
    if (index > 0) {
        VideoListModel *model = self.dataArray[index];
        self.isSelect = !self.isSelect;
        AVUser *user = [AVUser currentUser];
        if (user != nil) {
            if (self.isSelect) {
                [button setImage:[UIImage imageNamed:@"action_love_selected"] forState:UIControlStateNormal];
                AVObject *object = [[AVObject alloc] initWithClassName:@"URLTable"];
                [object setValue:model.mp4_url forKey:@"url"];
            
            
            }else {
                [button setImage:[UIImage imageNamed:@"action_love"] forState:UIControlStateNormal];
            }
        
        }else {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"未检测到登录用户,请登录!" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
            [alertVC addAction:action];
            [self presentViewController:alertVC animated:YES completion:nil];
        }
        
    }
    
    
}

#pragma mark - tableView代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ViewListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"videoCell" forIndexPath:indexPath];
    VideoListModel *model = self.dataArray[indexPath.row];
    [cell setValuesWithModel:model];
    [cell.playAndPause addTarget:self action:@selector(playAndPauseAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.shareButton addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.favorButton addTarget:self action:@selector(favorAction:) forControlEvents:UIControlEventTouchUpInside];
#pragma mark tag
    cell.playAndPause.tag = 100 + indexPath.row;
    cell.favorButton.tag = 200 + indexPath.row;
    cell.shareButton.tag = 300 + indexPath.row;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return (kheight - 64 - CGRectGetHeight(self.tabBarController.tabBar.frame)) / 2.0;
}



@end
